import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { createSwaggerConfig } from './swagger.config';
import { Logger } from '@nestjs/common';
import * as fs from 'fs';

const logger = new Logger('Bootstrap');
const PORT = process.env.PORT;
const DEVELOP_URL = `http://localhost:${PORT}`;
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // Swagger 配置
  const swaggerConfig = createSwaggerConfig();
  const document = SwaggerModule.createDocument(app, swaggerConfig);

  // 生产环境中关闭 Swagger
  if (process.env.NODE_ENV !== 'production') {
    SwaggerModule.setup('swagger', app, document);
    fs.writeFileSync('./swagger.json', JSON.stringify(document, null, 2));
    logger.log(`swagger地址: ${DEVELOP_URL}/swagger`);
  }

  app.use((req: any, res: any, next: any) => {
    logger.log(`Request to ${req.originalUrl}`);
    next();
  });
  // 日志中间件（如果需要的话可以加强日志功能）

  // 全局验证管道
  app.useGlobalPipes(new ValidationPipe());
  // 静态资源配置
  app.useStaticAssets(join(__dirname, '..', 'public'), { prefix: '/static' });
  app.useStaticAssets(join(__dirname, '..', 'public/videos'), {
    prefix: '/videos',
  });

  // 启动服务
  await app.listen(PORT);
  logger.log(`当前项目部署在 ${DEVELOP_URL}`);
}

bootstrap();
